<template>
  <div class="app-container">
    <el-row class="toolbar">
      <el-col :span="24">
        <el-form :inline="true" :model="filters">
          <el-select v-model="filters.status" placeholder="状态">
            <el-option
              v-for="(item,index) in optionStatus"

              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        <el-select v-model="filters.column" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="init">查询</el-button>
        </el-form-item>
        <el-form-item>
					  <el-button type="primary" @click="addDialogVisible=true"   v-if="hasPermission('system:user:add')">创建用户</el-button>
				</el-form-item>
      </el-form>
      </el-col>

    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table  :data="data.list" element-loading-text="Loading"  fit highlight-current-row>
          <el-table-column label='序号' width="95" type="index">
          </el-table-column>
          <el-table-column label="帐号" prop="account">
          </el-table-column>
          <el-table-column label="邮箱" prop="email">
          </el-table-column>
          <el-table-column label="电话" prop="phone">
          </el-table-column>
          <el-table-column label="角色">
            <template slot-scope="scope">
              <el-tag  size="mini" v-for="(roleKey,index) in scope.row.roleKeys.split(',')" :key="index">{{$store.state.common.roles[roleKey]}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="注册时间" width="160">
            <template slot-scope="scope">
              {{scope.row.time/1000|moment("YYYY-MM-DD HH:mm:ss")}}
            </template>
          </el-table-column>
          <el-table-column label="禁用">
            <template slot-scope="scope">
              <el-switch disabled  v-model="scope.row.disabled" active-color="#ff4949"  inactive-color="#13ce66"> </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tag size="mini" :type="scope.row.status===1?'success':'info'">{{scope.row.status===1?'在线':'离线'}}</el-tag>

            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="260">
            <template slot-scope="scope">
              <el-button size="small" type="warning" @click="allocationCar(scope.row)">分配车辆</el-button>
              <el-button size="small" type="success" @click="goTrack(scope.row)">监控</el-button>
                <el-button size="small" type="primary" @click="handleEdit(scope.row)" v-if="hasPermission('system:user:update')">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-if="hasPermission('system:user:delete')">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-col>
    </el-row>
    <el-row class="toolbar">
      <el-col :span="24">
        <el-pagination
         layout="total, sizes, prev, pager, next"
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
        :page-sizes="this.$store.state.common.pageSizes"
        :page-size="this.$store.state.common.pageSize"
        :total="data.total"
        style="float:right;">
        </el-pagination>
      </el-col>
      </el-col>
    </el-row>


    <el-dialog
    title="创建用户"
    :visible.sync="addDialogVisible"
    width="40%"
    >
    <el-form :model="addForm" ref="addValidateForm" label-width="100px" class="demo-ruleForm">
      <el-form-item  label="帐号" prop="account" :rules="[{ required: true, message: '帐号不能为空'}]" >
        <el-input v-model="addForm.account" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item  label="邮箱"  prop="email" :rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}]">
        <el-input v-model="addForm.email" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item  label="电话"  prop="phone" :rules="[{ min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur'}]">
        <el-input v-model="addForm.phone" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
        :rules="[{ required: true, message: '密码不能为空'}]"
      >

        <el-input v-model="addForm.password" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="password2"
        :rules="[{ required: true, message: '确认密码不能为空'}]"
      >
        <el-input v-model="addForm.password2" auto-complete="off"></el-input>
      </el-form-item>
     <el-form-item label="角色" prop="roleIds" :rules="[{ required: true, message: '请选择角色'}]">
       <el-checkbox-group v-model="addForm.roleIds">
         <el-checkbox v-for="(role,index) in roles"   :key="index" :label="role.id"  :disabled="role.roleKey==='root'">{{role.name}}</el-checkbox>

       </el-checkbox-group>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addSubmit">确 定</el-button>
    </span>
  </el-dialog>


    <el-dialog
    title="修改用户"
    :visible.sync="editDialogVisible"
    width="40%"
    >
    <el-form :model="editForm" ref="editValidateForm" label-width="100px" class="demo-ruleForm">
      <el-form-item  label="帐号"  prop="account">
        <el-input v-model.number="editForm.account" auto-complete="off" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item  label="邮箱"  prop="email" :rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}]">
        <el-input v-model="editForm.email" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item  label="电话"  prop="phone" :rules="[{ min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur'}]">
        <el-input v-model="editForm.phone" auto-complete="off"></el-input>
      </el-form-item>
     <el-form-item label="角色" prop="parentId">
       <el-checkbox-group v-model="editForm.roleIds">
         <el-checkbox v-for="(role,index) in roles"  :key="index" :label="role.id" :disabled="role.roleKey==='root'">{{role.name}}</el-checkbox>

       </el-checkbox-group>
    </el-form-item>
    <el-form-item label="禁用" prop="disabled">
      <el-switch
      v-model="editForm.disabled"
      active-color="#ff4949"
      inactive-color="#13ce66"
      active-text="是"
      inactive-text="否"
      >
    </el-switch>
   </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editSubmit">确 定</el-button>
    </span>
  </el-dialog>

    <el-dialog
      title="分配车辆"
      :visible.sync="allocationCarVisible"
      width="40%">
      <el-row>
        <el-col :span="18">
          <el-input v-model.number="searchDevicesKey" placeholder="请输入设备名称"></el-input>
        </el-col>
        <el-col :offset="1" :span="5">
          <el-button @click="searchDevices" type="primary">搜索</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="deviceTableData"
        @current-change="deviceCurrentChange"
        highlight-current-row
        style="width: 100%">
        <el-table-column
          prop="name"
          label="设备名称">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="allocationCarVisible = false">取 消</el-button>
        <el-button type="primary" @click="allocationCarSubmit">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { getUserList,deleteUser,getRoles,updateUser,userAdd,generateToken, selDevice, linkAccount } from '@/api/api'

export default {
  data() {
    return {
      page: 1,
      data:{},
      optionStatus:[
          {
           value: -1,
           label: '全部'
         },
          {
           value: 1,
           label: '在线'
         },{
          value: 0,
          label: '离线'
        }
      ],
      filters: {
          column:'',
          keyword:'',
          status:-1
        },
        options: [{
           value: 'account',
           label: '账号'
         }, {
           value: 'email',
           label: '邮箱'
         }, {
           value: 'phone',
           label: '电话'
         }],
      editDialogVisible:false,
      addDialogVisible:false,
      allocationCarVisible: false,
      deviceTableData: [],
      currentUserRow: {},
      currentDevice: {},
      searchDevicesKey: '',
      editForm:{
        roleIds:[]
      },
      addForm:{
        phone: '',
        disabled: false,
        email: '',
        roleIds:[]
      },
      roles:[]
    }

  },
  created() {
    this.init();
    this.getRoles();
    //console.log();
  },
  methods: {
    deviceCurrentChange (row) {
      this.currentDevice = row
    },
    searchDevices () {
      selDevice({
        name: this.searchDevicesKey
      }).then(data => {
        console.log(data, 988)
        this.deviceTableData = data
      })
    },
    allocationCarSubmit () {
      linkAccount({
        userId: this.currentUserRow.id,
        deviceId: this.currentDevice.id
      }).then(data => {
        this.allocationCarVisible = false
        this.$notify({
          title: '提示',
          message: '分配成功',
          type: 'success'
        })
      })
    },
    allocationCar (row) {
      this.currentUserRow = row
      this.allocationCarVisible = true
    },
    init() {
      let para = {
        page: this.page,
        pageSize:this.$store.state.common.pageSize,
        column:this.filters.column,
        keyword:this.filters.keyword,
        status:this.filters.status
      };
      getUserList(para).then(data => {
        this.data = data
      })
    },
    handleDelete(row){
      deleteUser(row.id).then(data => {
        this.init()
      })
    },
    handleEdit(row){
      this.editForm=row;
      if(row.roleIds  instanceof Array){

      }else{
        let arrs = row.roleIds.split(',');
        let roles = [];
        for(var i=0;i<arrs.length;i++){
          roles.push(parseInt(arrs[i]))
        }
        this.editForm.roleIds=roles;
      }

      this.editDialogVisible=true;
    },
    editSubmit(){
        this.$refs.editValidateForm.validate((valid) => {
            if (valid) {
                  this.editDialogVisible=false;
                  updateUser(this.editForm).then(data => {
                      this.init()
                  })
              }
        });
    },
    getRoles(){
      getRoles().then(data => {
        this.roles = data
      })
    },
    addSubmit(){
        this.$refs.addValidateForm.validate((valid) => {
          if (valid) {
            userAdd(this.addForm).then(data => {
                this.addDialogVisible=false;
                  this.init();
            })
          }else{
             return false;
          }
        });
    },
    handleSizeChange(val) {
      this.$store.dispatch('updatePageSize',val);
      this.init();

     },
     handleCurrentChange(val) {
       this.page = val;
       this.init();
     },
     goTrack(row){
          generateToken(row.id).then(data => {
            let monitorUser = {account:row.account,token:data}
            localStorage.monitorUser = JSON.stringify(monitorUser);
            window.open('#/map');
          })

     },
  }
}
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

</style>
